<template>
  <div class="app-container">

    <el-input placeholder="名称" v-model="example.title" style="width: 150px"></el-input>
    <el-input placeholder="演唱者" v-model="example.players" style="width: 200px"></el-input>
    <el-select placeholder="类型" v-model="example.genre" style="width: 150px">
      <el-option
        v-for="item in genreOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
    <span style="display: inline-flex;align-items: center;width:250px;margin-left: 15px">
        <span style="color:#606266;font-weight:700;font-size:14px;margin-right:20px !important;}">分数范围</span>
        <el-slider v-model="sliderValue" :step="0.1" :max="10" style="width: 150px;" range></el-slider>
    </span>

    <el-button icon="el-icon-search" @click="fetchData" type="primary" round style="margin-left: 10px;">搜索</el-button>
    <el-button icon="el-icon-refresh" @click="reset" circle></el-button>


    <el-table :data="list" v-loading.body="listLoading" element-loading-text="加载数据中" fit
              highlight-current-row style="margin-top: 20px;">
      <el-table-column type="expand" label='详情'>
        <template slot-scope="scope">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-card style="width:200px ;height:200px" :body-style="{margin: '0',padding: '0'}">
                <el-image
                  style="width: 200px; height: 200px"
                  :src="scope.row.imgUrl"
                  fit="fill"
                  referrerpolicy="never"

                ></el-image>
              </el-card>
            </el-col>
            <el-col :span="18">
              <el-row>
                <div style="display: -webkit-box;
                        -webkit-box-orient: vertical;
                         -webkit-line-clamp: 3;
                        height: 66px;
                        text-overflow: ellipsis;
                        overflow: hidden;line-height: 22px;font-size: 14px;text-indent:28px;"
                >{{scope.row.introduction}}
                </div>
              </el-row>
              <el-row style="height: 150px">
                <el-col :span="6">
                  <el-form label-position="left"
                           style="margin-right: 0px;
                              margin-top: 10px;
                              margin-bottom: 0;
                              width: 100%;" size="mini">
                    <el-form-item label="介质" v-if="scope.row.medium">
                      <span>{{ scope.row.medium }}</span>
                    </el-form-item>
                    <el-form-item label="种类" v-if="scope.row.type">
                      <span>{{ scope.row.type }}</span>
                    </el-form-item>
                    <el-form-item label="发行日期" v-if="scope.row.publishTime">
                      <span>{{ scope.row.publishTime | dateReserve }}</span>
                    </el-form-item>
                    <el-form-item label="总评分数" v-if="scope.row.reviewAmount">
                      <span>{{ scope.row.reviewAmount }}</span>
                    </el-form-item>
                  </el-form>
                </el-col>
                <el-col :span="18" style="height: 150px">
                  <ve-line :data="scope.row | proportionFilter"
                           :settings="chartSettings"
                           height="150px"
                           :legend-visible="false"
                           :tooltip-visible="false"
                           :extend="{series: {label: {normal: {
                           show: true,formatter:'{@[1]}%'}}}}"
                           :yAxis="{show:false}"
                           :grid="{top:'15%',bottom:'20%',right:0}"
                           :colors="['#ff9900']"
                           :title="{text:'评分比例',top:'10%',left:'10%',textStyle:{color:'#606266',fontWeight:'700',fontSize:'14'}}"
                  ></ve-line>
                </el-col>
              </el-row>
              <el-row style="display: flex;justify-content: flex-end">
                 <span style="display: flex;align-items: center;margin: 0 20px;">
                  <svg-icon icon-class="douban" style="font-size: 28px"/>
                  <el-link type="success" style="color: #2B7F4D" target="_blank"
                           :href="'https://music.douban.com/subject/'+scope.row.bdid+'/'">前往豆瓣页面</el-link>
                </span>
                <span style="margin-right: 15px">
                  <el-button @click="toModifydetail(scope.row)" type="info" circle size="small"
                             icon="el-icon-edit"></el-button>
                  <el-button @click="changeStatus(scope.row.bdid,-1)" type="danger" circle size="small"
                             icon="el-icon-delete"></el-button>
                </span>

              </el-row>

            </el-col>
          </el-row>
          <el-row v-if="false">
            <template v-for="bdid in imgUrlComputed(scope.row.relatednessBdid)">
              <el-card style="width:100px ;height:100px;display: inline-block" :body-style="{margin: '0',padding: '0'}">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="imgUrlComputed(bdid)"
                  fit="fill"
                  referrerpolicy="never"

                ></el-image>
              </el-card>
            </template>

          </el-row>
        </template>
      </el-table-column>

      <el-table-column align="center" label='名称'>
        <template slot-scope="scope">
          {{scope.row.title}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="演唱者" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.players | playersFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发布商" width="120">
        <template slot-scope="scope">
          {{scope.row.publisher}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类" width="110">
        <template slot-scope="scope">
          {{scope.row.genre}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="豆瓣评分" width="200">
        <template slot-scope="scope">
          <el-rate
            v-model="scope.row.score / 2"
            :max=5
            disabled
            style="display: inline-block"
            :allow-half=true
            text-color="#ff9900"
            score-template="{value}">
          </el-rate>
          <b style="color: #ff9900">{{scope.row.score}}</b>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="120">
        <template slot-scope="scope">
          <el-button @click="changeStatus(scope.row.bdid,1)" type="text" circle size="small" style="padding: 2px">
            <svg-icon icon-class="like" style="font-size: 22px;color: #bdbdbd"
                      :class="{yellow: (scope.row.status === 1)}"/>
          </el-button>
          <el-button @click="changeStatus(scope.row.bdid,2)" type="text" circle size="small" style="padding: 2px">
            <svg-icon icon-class="star" style="font-size: 22px;color: #bdbdbd"
                      :class="{yellow: (scope.row.status === 2)}"/>
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <Pagination
      :total="total"
      :page.sync="page"
      :limit.sync="limit"
      @pagination="fetchData"/>

    <el-dialog title="修改信息" :visible.sync="dialogFormVisible">
      <el-form :model="temp">
        <el-form-item label="音乐ID" :label-width="formLabelWidth">
          <el-input v-model="temp.bdid" disabled></el-input>
        </el-form-item>
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="temp.title"></el-input>
        </el-form-item>
        <el-form-item label="介质" :label-width="formLabelWidth">
          <el-input v-model="temp.medium"></el-input>
        </el-form-item>
        <el-form-item label="分类" :label-width="formLabelWidth">
          <el-input v-model="temp.genre"></el-input>
        </el-form-item>
        <el-form-item label="发布商" :label-width="formLabelWidth">
          <el-input v-model="temp.publisher"></el-input>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth">
          <el-input :autosize="{ minRows: 2, maxRows: 4}" type="textarea" v-model="temp.introduction"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="modifyData">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {search, getImgUrl, modify, deleteMusic, fetchGenres, changeStatus} from '@/api/music'
  import Pagination from '@/components/Pagination'
  import {mapGetters} from 'vuex'

  export default {
    components: {Pagination},
    data() {
      this.chartSettings = {

        area: true
      };
      return {
        list: null,
        listLoading: true,
        buttonLoading: false,
        dialogFormVisible: false,
        formLabelWidth: "120",
        total: 20,
        page: 1,
        limit: 10,
        example: {
          title: '',
          players: '',
          genre: ''
        },
        sliderValue: [0, 10],
        temp: {},
        genreOptions: []

      }
    },
    filters: {
      playersFilter(data) {
        let players = JSON.parse(data);
        let result = '';
        for (let player of players) {
          result = result + ' ' + player + ' '
        }
        return result
      },
      proportionFilter(data) {
        let result = {
          columns: ['星级', '比例'],
          rows: [
            {'星级': '1星', '比例': data.star1Proportion},
            {'星级': '2星', '比例': data.star2Proportion},
            {'星级': '3星', '比例': data.star3Proportion},
            {'星级': '4星', '比例': data.star4Proportion},
            {'星级': '5星', '比例': data.star5Proportion},
          ]
        };
        return result
      },
      dateReserve(timestamp) {
        var date = new Date(timestamp * 1000);
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() + 1 < 10 ? '0' + (date.getDate() + 1) : date.getDate() + 1);
        return Y + M + D;
      }
    },
    created() {
      this.fetchData();
      this.fetchGenreOptions();
      this.checkLogin()
    },
    computed: {
      ...mapGetters([
        'uid'
      ]),
    },
    methods: {
      async logout() {
        await this.$store.dispatch('user/logout');
        this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      },
      checkLogin() {
        if (!this.uid) {
          this.logout();
          return false
        }
      },
      fetchGenreOptions() {
        fetchGenres().then(response => {
          var i = 0;
          for (var item of response.data) {
            var set = {};
            set.value = item;
            this.genreOptions[i] = set;
            i++
          }
        })
      },
      imgUrlComputed(bdidList) {
        var url = [];
        bdidList = JSON.parse(bdidList);
        for (let bdid of bdidList) {
          getImgUrl({
            bdid: bdid
          }).then(response => {
            url.push(response.data);
          })
        }
        return url
      }, //todo 异步问题未解决
      fetchData() {
        this.listLoading = true;
        search({
          page: this.page, limit: this.limit, uid: this.uid,
          title: this.example.title, players: this.example.players, genre: this.example.genre,
          slider_begin: this.sliderValue[0], slider_end: this.sliderValue[1]
        }).then(response => {
          this.list = response.data;
          this.total = response.count;
          this.listLoading = false
        })
      },
      reset() {
        for (var key in this.example) {
          this.example[key] = '';
        }
        this.sliderValue = [0, 10];
        this.fetchData();
      },
      toModifydetail(rowData) {
        this.temp = Object.assign({}, rowData);
        this.dialogFormVisible = true
      },
      modifyData() {
        this.buttonLoading = true;
        modify(this.temp).then(response => {
          this.buttonLoading = false;
          this.dialogFormVisible = false;
          this.$message({
            type: 'success',
            message: '修改成功'
          });
          this.fetchData()
        })
      },
      changeStatus(id, statusCode) {
        changeStatus({bdid: id, uid: this.uid, status: statusCode}).then(response => {
          // this.$message({
          //   type: 'success',
          //   message: response.msg
          // });
          let flag = 0;
          for (let item of this.list) {
            if (item['bdid'] === id) {
              if (statusCode === -1) {
                this.fetchData();
                return false
              }
              if (item['status'] === statusCode) {
                this.list[flag].status = 0
              } else {
                this.list[flag].status = statusCode
              }
            }
            flag += 1
          }

        })
      }


    }
  }
</script>

<style scoped rel="stylesheet/scss" lang="scss">
  .el-form-item {
    margin-bottom: 0 !important;
  }

  .yellow {
    fill: #ff9900 !important;
  }
</style>
